(function (angular) {
  var module = angular.module('base', []);

  module.controller('BaseCtrl', function($scope, $http) {
    $scope.longUrl = '';

    $scope.shortenUrl = function() {
      // If URL doesn't start with 
      var longUrl = $scope.longUrl || '';
      if (longUrl.toLowerCase().indexOf('http') != 0) {
        longUrl = 'http://' + longUrl;
      }
      $http.post('/new', {longUrl: longUrl})
          .success(function(data, status, headers, config) {
            $scope.shortUrl = 'www.orp.io/' + data.ShortUrl;
            $scope.errorText = '';
          })
          .error(function(data, status, headers, config) {
            $scope.errorText = data;
            $scope.shortUrl = '';
          });
    };
  });

  module.directive('selectOnClick', function () {
    return function (scope, element, attrs) {
      element.bind('click', function () {
        this.select();
      });
    };
  });

  // Works only for container elements.
  module.directive('hiddenWhenEmpty', function() {
    return function(scope, element, attrs) {
      if (element[0].innerText == '') {
        element[0].style.visibility = 'hidden';
      } else {
        element[0].style.visibility = 'visible';
      }
    }
  });
}(angular));
